package com.wanmait.heating.webcontroller;


import com.alibaba.fastjson.JSONObject;
import com.wanmait.heating.pojo.Userinfo;
import com.wanmait.heating.service.UserinfoService;
import com.wanmait.heating.utils.CookieUtils;
import com.wanmait.heating.utils.EncryptUtils;
import com.wanmait.heating.utils.MD5Utils;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
public class WebCommonController {
    @Autowired
    private UserinfoService userinfoService;


    //访问前台界面的首页
    @RequestMapping("web/index")
    public void index()
    {
    }

    //退出前台界面
    @RequestMapping("web/exit")
    public String exit(HttpServletRequest request,HttpServletResponse response)
    {
        //清空session
        request.getSession().removeAttribute("loginUser");
        //清空cookie
        CookieUtils.write("name", "", "/", 0, response);
        CookieUtils.write("password", "", "/", 0, response);
        return "redirect:/user/login";
    }



    //访问用户前台的注册界面
    @GetMapping("user/registe")
    public void registe() {}


    /*登录==================================================================*/
    //访问用户前台的登录界面
    @GetMapping("user/login")
    public void  login() {

    }

    //密码登录 登录去往首页，带着用户名和密码
    @PostMapping("user/login")
    public String loginSubmit(HttpServletRequest request, HttpServletResponse response,String password, String name, String remberMe)
    {
        HttpSession session = request.getSession();
        Userinfo userinfo = new Userinfo();

        userinfo.setName(name);
        if(password!=null){
            //对密码进行md5加密
            userinfo.setPassword( MD5Utils.md5(password));
        }
        Userinfo userinfox = userinfoService.isExist(userinfo);
        session.setAttribute("loginUser", userinfox);
        session.setMaxInactiveInterval(60*60*24*30);
        //判断是否记住我
        if(remberMe!=null)
        {
            //写cookie
            CookieUtils.write("name", EncryptUtils.encrypt(name,3),"/",60*60*24*30,response);
            CookieUtils.write("password",userinfo.getPassword(),"/",60*60*24*30,response);
        }
        //去首页
        return "redirect:/user/usercenter/index";
    }



    //ajax访问短信登录页面
    @RequestMapping("user/AjaxMesLogin")
    public String changeMesLogin(){
        return "redirect:/user/mesLogin";
    }

    //ajax访问密码登录页面
    @RequestMapping("user/AjaxPassLogin")
    public String changePassLogin(){
        return "user/passLogin";
    }

    //更换页面
    @RequestMapping("user/mesLogin")
    public void mesLgoin (){
    }

    //更换页面
    @RequestMapping("user/passLogin")
    public void passLgoin (){
    }


    /*注册==================================================================*/

    //查看用户手机号是否注册过
    @RequestMapping("/isRegiste")
    @ResponseBody
    public String isRegiste(Userinfo userinfo)
    {

        if(userinfo.getPassword()!=null||userinfo.getPassword()!=""){
            String password = MD5Utils.md5(userinfo.getPassword());
            userinfo.setPassword(password);

        }
        Userinfo existUserinfo = userinfoService.isExist(userinfo);
        //没有注册过返回true ;
        if(existUserinfo==null)
        {
            return "true";
        }else
        {
            return "false";
        }
    }

    //查看昵称是否存在
    @RequestMapping("isExist")
    @ResponseBody
    public String isExist(String name)
    {
        System.out.println(name);
        Userinfo userinfo = new Userinfo();
        userinfo.setName(name);
        Userinfo existUserinfo = userinfoService.isExist(userinfo);
       if(existUserinfo==null)
       {
           return "true";
       }
       else
       {
           return "false";
       }
    }

    //发送短信验证码
    @RequestMapping("/sendSms")
    @ResponseBody
    public Object sendSms(HttpServletRequest request, String number) {
        System.out.println("手机号"+number);
        try {
            JSONObject json = null;
            //生成6位验证码
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            System.out.println("随机验证码："+verifyCode);
            //发送短信
            ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "107023","4edc23b4-4df7-4742-b77a-12d322fb4ef8");



            Map<String, Object> params = new HashMap<String, Object>();
            params.put("number", number);
            params.put("templateId", "2084");
            String[] templateParams = new String[2];
            templateParams[0] = verifyCode;//验证码
            templateParams[1] = "5";//时间   5分钟
            params.put("templateParams", templateParams);
            String result = client.send(params);
            System.out.println("result="+result);

            json = JSONObject.parseObject(result);
            if(json.getIntValue("code") != 0)//发送短信失败
                return "fail";
            //将验证码存到session中,同时存入创建时间
            //以json存放，这里使用的是阿里的fastjson
            HttpSession session = request.getSession();
            json = new JSONObject();
            json.put("verifyCode", verifyCode);
            json.put("createTime", System.currentTimeMillis());
            // 将认证码存入SESSION
            request.getSession().setAttribute("verifyCode", json);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/checkCode")
    @ResponseBody
    public String checkCode(HttpServletRequest request, String number, String verifyCode) {
        try {
            JSONObject json = (JSONObject)request.getSession().getAttribute("verifyCode");
            if(json.getString("verifyCode")==null||json.getString("verifyCode").equals("")) {
                System.out.println("验证码空");
                return "验证码错误";
            }
            if(!json.getString("verifyCode").equals(verifyCode)){
                System.out.println("验证码错误");
                return "验证码错误";
            }
            if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
                System.out.println("验证码过期");
                return "验证码过期";
            }
            System.out.println("成功");
            return "success";
        } catch (Exception e) {
            System.out.println("cuowu");
            return  "验证码错误";
        }
    }

    //注册成功去往登录界面
    @PostMapping("/registe")
    public String registeSubmit(HttpServletRequest request, String password, String name)
    {
        //注册
        Userinfo userinfo = new Userinfo();
        userinfo.setName(name);
        userinfo.setPhone(name);
        //对密码进行md5加密
        String md5Password = MD5Utils.md5(password);
        userinfo.setPassword(md5Password);
        userinfoService.insert(userinfo);
        return "redirect:/user/login";
    }
}
